var sha = require('sha.js')
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
var Sign = {};

//创建随机字符串
Sign.createNonceStr = function () {
  return Math.random().toString(36).substr(2, 15);
};
//获取当前时间戳
Sign.createTimestamp = function () {
  return parseInt(new Date().getTime() / 1000) + '';
};
//对参数进行排序
Sign.raw = function (args) {
  var keys = Object.keys(args);
  keys = keys.sort();
  var newArgs = {};
  keys.forEach(function (key) {
    newArgs[key.toLowerCase()] = args[key];
  });

  var string = '';
  for (var k in newArgs) {
    // string += '&' + k + '=' + newArgs[k];
    string += k + newArgs[k];
  }
  //string = string.substr(1);
  return string;
};
/**
 * @synopsis 签名算法
 *
 * @param jsapi_ticket 用于签名的 jsapi_ticket
 * @param url 用于签名的 url ，注意必须动态获取，不能 hardcode
 *
 * @returns
 */
Sign.sign = function () {
  var ret = {
    code: '',
    openid: '',
    nonce_str: Sign.createNonceStr(),
    timestamp: Sign.createTimestamp()
  };
  ret.signature = Sign.doSign(ret);
  return ret;
};
//对参数对象进行签名
Sign.doSign = function (ret) {
  var string = Sign.raw(ret);
  ///G.d('doSign params string = '+ string);
  var shaObj = new sha.jsSHA(string, 'TEXT');
  return shaObj.getHash('SHA-1', 'HEX');
};

//校验手机号码
var testPhone = function (phone) {
  if (phone) {
    var reg = /^0?1[3|4|5|7|8][0-9]\d{8}$/;
    if (reg.test(phone)) {
      return true;
      // callback(true);
    } else {
      return false;
      // callback(false);
      //P.alertMsg("警告", "请输入有效的手机号码!");
    }
  } else {
    return false;
    // callback(false);
    //P.alertMsg("警告", "请输入手机号!");
  }
}
// 提示弹窗
var modalMsg = function (title, content, confirm, cancel, showCancel, confirmText, confirmColor,cancelText, cancelColor, ) {
  // confirm 确认回掉函数 cancel 取消回掉函数
  if (showCancel == null || showCancel == '' && showCancel != false) { showCancel = true }
  if (confirmText == null || confirmText == '') { confirmText = '确定' }
  if (confirmColor == null || confirmColor == '') { confirmColor = '#5ca146' }
  if (cancelText == null || cancelText == '') { cancelText = '取消' }
  if (cancelColor == null || cancelColor == '') { cancelColor = '#333' }
  wx.showModal({
    title: title, // 标题
    content: content,   // 提示的内容
    showCancel: showCancel,   // 是否显示取消按钮，默认为 true
    cancelText: cancelText,   // 取消按钮的文字，默认为"取消"，最多 4 个字符
    cancelColor: cancelColor, // 取消按钮的文字颜色，默认为"#000000"
    confirmText: confirmText, // 确定按钮的文字，默认为"确定"，最多 4 个字符
    confirmColor: confirmColor,   // 确定按钮的文字颜色，默认为"#3CC51F"
    success: function (res) {   
      if (res.confirm) {
        // 用户点击 确认按钮
        confirm(res.confirm);
      } else if (res.cancel) {
        // 用户点击 取消按钮
        cancel(res.cancel);
      }
    },
    fail:function(res){
      toastMsg('请稍后再试','none')
    }
  })
}
//显示消息提示框
var toastMsg = function (title, icon, image, duration, mask){
  // icon = success / loading / none
  // image = 自定义图标的本地路径，image 的优先级高于 icon
  // duration = 提示的延迟时间
  // mask = 是否显示透明蒙层
  if (icon == null || icon == '') { icon = 'success' }
  if (duration == null || duration == '') { duration = 1500}
  if (mask == null || mask == '') { mask = true }
  wx.showToast({
    title: title,
    icon: icon,
    image: image,
    duration: duration,
    mask: mask
  })
}
//身份证号合法性验证 
//支持15位和18位身份证号
//支持地址编码、出生日期、校验位验证
var IdentityCodeValid = function (code) {
  var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
  var tip = "";
  var pass = true;

  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
    tip = "身份证号格式错误";
    pass = false;
  }

  else if (!city[code.substr(0, 2)]) {
    tip = "地址编码错误";
    pass = false;
  }
  else {
    //18位身份证需要验证最后一位校验位
    if (code.length == 18) {
      code = code.split('');
      //∑(ai×Wi)(mod 11)
      //加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      //校验位
      var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
      var sum = 0;
      var ai = 0;
      var wi = 0;
      for (var i = 0; i < 17; i++) {
        ai = code[i];
        wi = factor[i];
        sum += ai * wi;
      }
      var last = parity[sum % 11];
      if (parity[sum % 11] != code[17]) {
        tip = "校验位错误";
        pass = false;
      }
    }
  }
  if (!pass) {
    return tip;
  } else {
    return null;
  }
}
// 链接
function buttonClicked(self) {
  self.setData({
    buttonClicked: true
  })
  setTimeout(function () {
    self.setData({
      buttonClicked: false
    })
  }, 500)
}
module.exports = {
  formatTime: formatTime,
  testPhone: testPhone,
  modalMsg: modalMsg,
  toastMsg: toastMsg,
  sign: Sign,
  IdentityCodeValid: IdentityCodeValid,
  buttonClicked: buttonClicked
}
